package com.wolves.career.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wolves.career.entity.IndustryInformationClassification;
import com.wolves.career.entity.excel.InfoExcel;
import com.wolves.career.service.IndustryInformationClassificationService;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.BeanUtils;

import java.util.Map;
import java.util.Random;

/**
 * @author 麦翔盛
 * @description: excel的监听器
 * 添加分分类
 * @date 2021/10/25 19:20
 */
@AllArgsConstructor
@NoArgsConstructor
@Data
public class ClassificationExcelListener extends AnalysisEventListener<InfoExcel> {
    private IndustryInformationClassificationService classificationService;

    /**
     * 一行一行的读取信息
     *
     * @param infoExcel
     * @param analysisContext
     */
    @Override
    public void invoke(InfoExcel infoExcel, AnalysisContext analysisContext) {
        Random random = new Random();
        if (infoExcel == null) {
            return;
        }
        //判断标题是否重复
        boolean exist = this.existClassification(classificationService, infoExcel.getClassification());

        IndustryInformationClassification classification = new IndustryInformationClassification();
//            BeanUtils.copyProperties(infoExcel,classification);
        if (!exist) {
        //如果没有该类别才添加
        classification.setClassification(infoExcel.getClassification());
        System.out.println(infoExcel.getClassification());
        //设置阅读量
        classification.setCount(random.nextInt(10000));
        //保存
        classificationService.save(classification);
    }

    }

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        System.out.println("标题:" + headMap);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    /**
     * 判断该资讯分类是否重复
     *
     * @param classificationService
     * @param classification
     * @return
     */
    public boolean existClassification(IndustryInformationClassificationService classificationService, String classification) {
        QueryWrapper<IndustryInformationClassification> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("classification", classification);
        IndustryInformationClassification exist = classificationService.getOne(queryWrapper);
        if (exist != null) {
            return true;
        }
        return false;
    }
}
